//
//  GZViewController.swift
//  mggz
//
//  Created by Apple on 2018/4/19.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import SVProgressHUD
import RxSwift
import RxCocoa
import MJRefresh

class GZViewController: UIViewController {
    @IBOutlet weak var rightImge: UIImageView!
    @IBOutlet weak var userlayout: UIView!
    @IBOutlet weak var userLabel: UILabel!
    @IBOutlet weak var tableview: UITableView!
    @IBOutlet weak var totaltableview: UITableView!
    @IBOutlet weak var selectline: UIView!
    var page:Int = 1
    
    var entity:GZTotal?
    
    @IBOutlet weak var totaltableHeight: NSLayoutConstraint!
    var disposeBag:DisposeBag = DisposeBag()
    var datavariable:PublishSubject<[GZTotalItem]> = PublishSubject()
    var data=[GZTotalItem]()
    
    var selectBag:DisposeBag = DisposeBag()
    var selectvariable:PublishSubject<[(String,String)]> = PublishSubject()
    var selectdata = [(String,String)]()
    
    let rowSelectHeight:CGFloat = 35
    var emptyview:EmptyView?
    var tableNormalFoot:MJRefreshBackNormalFooter?
    var tableHeader:MJRefreshNormalHeader?
    
    
    lazy var tapOpen:UITapGestureRecognizer = {
        var tap = UITapGestureRecognizer(target: self, action: #selector(click(_:)))
        tap.numberOfTapsRequired = 1
        tap.numberOfTouchesRequired = 1
        return tap
    }()
    
    lazy var transform:CGAffineTransform = {
       var trans = CGAffineTransform(rotationAngle: 90/180)
        return trans
    }()
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        SVProgressHUD.setMaximumDismissTimeInterval(1.0)
        
        self.totaltableview.backgroundColor = UIColor.LightGrey
        self.rightImge.transform = CGAffineTransform(rotationAngle: CGFloat(90*Double.pi/180))

        self.tableview.register(UINib(nibName: "GZItem", bundle: nil), forCellReuseIdentifier: "cell")
        self.totaltableview.isScrollEnabled = false
        self.totaltableview.register(UINib(nibName: "GZSelectViewTableViewCell", bundle: nil), forCellReuseIdentifier: "titlecell")
        self.totaltableview.separatorStyle = .none
        self.tableview.tableFooterView=UIView(frame: CGRect.zero)
        self.tableview.separatorStyle = .none
        self.totaltableview.tableFooterView=UIView(frame: CGRect.zero)
        //self.totaltableview.estimatedRowHeight = 50
        self.totaltableview.rowHeight = self.rowSelectHeight
        self.tableview.rowHeight = 130
        self.datavariable.asObservable().bind(to: self.tableview.rx.items){
            (_,row,element) in
            let cell = self.tableview.dequeueReusableCell(withIdentifier: "cell", for: IndexPath(row : row, section : 0)) as! GZItem
            cell.itemData = element
            cell.selectionStyle = UITableViewCellSelectionStyle.none
            print("\(cell.bounds.width)---\(ScreenWidth)")
            //cell.line.drawline(10, _lineSpacing: 2, _lineColor: UIColor.black)
            //customize cell
            return cell
            }.disposed(by: self.disposeBag)
        
        self.selectvariable.asObservable().bind(to: self.totaltableview.rx.items){
            (_,row,element) in
            let cell = self.totaltableview.dequeueReusableCell(withIdentifier: "titlecell", for: IndexPath(row : row, section : 0)) as! GZSelectViewTableViewCell
            cell.itemdata = element
            cell.selectionStyle = UITableViewCellSelectionStyle.none
            cell.deleget = {
                print("点击")
                let balanceController = BalanceController(nibName: "BalanceController", bundle: nil)
                self.navigationController?.pushViewController(balanceController, animated: true)
            }
            //customize cell
            return cell
            }.disposed(by: self.selectBag)
        
        self.totaltableview.rx.modelSelected((String,String).self).subscribe { (event) in
            print("\(event.element?.1)")
        }
        
        self.tableHeader = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(refresh))
        self.tableHeader?.stateLabel.isHidden = true
        self.tableview.mj_header = self.tableHeader
        
        self.tableNormalFoot = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadMore))
        self.tableNormalFoot?.stateLabel.isHighlighted = true
        self.tableview.mj_footer = tableNormalFoot
        
        self.userlayout.isUserInteractionEnabled = true
        self.userlayout.addGestureRecognizer(self.tapOpen)
        
        getTotalData()
        //self.tableview.mj_footer.isAutomaticallyHidden = true
    }
    
    @objc func loadMore(){
        self.page += 1
        self.tableNormalFoot?.stateLabel.isHighlighted = true
        self.getTotalList()
    }
    
    @objc func refresh(){
        self.page = 1
        self.tableNormalFoot?.stateLabel.isHighlighted = true
        self.getTotalList()
    }
    
    @objc func click(_ tap:UIGestureRecognizer){
        print("打开")
        if self.selectdata.count > 0 {
            
            if self.totaltableHeight.constant == 0{
                self.totaltableHeight.constant = CGFloat(self.selectdata.count) * self.rowSelectHeight
                UIView.animate(withDuration: 0.5) {
                    self.rightImge.transform = CGAffineTransform(rotationAngle: CGFloat(90*Double.pi/180))
                    self.view.layoutIfNeeded()
                }
            }else{
                self.totaltableHeight.constant = 0
                UIView.animate(withDuration: 0.5) {
                    self.rightImge.transform = CGAffineTransform(rotationAngle: 0/180)
                    self.view.layoutIfNeeded()
                }
            }
            
            
        }
        
        
    }
    
    
    func getTotalData(){//payedSalaryAmount  advaceSalaryAmount
        var param:[String:Any] = ["constructionProjectID":ProjectId as! String];
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .GZTotal, params: &param, type: GZTotal.self, success: { (bean,_) in
            self.entity = bean as! GZTotal
            self.userLabel.text = "\(((self.entity?.Result?.ResidualAmount ?? 0).roundTo(2)))元"
            //self.selectdata.append(("已付工资：","\((b.Result?.PayedSalaryAmount)!)元"))
            if (self.entity?.Result?.IsFlat)! && (self.entity?.Result?.IsSignSalary)!{
                print("平台")
                self.selectdata.append((("已请款工资："),"\(((self.entity?.Result?.ApplyedSalaryAmount ?? 0).roundTo(2)))元"))
                self.selectdata.append(("剩余可请款工资：","\(((self.entity?.Result?.NonApplySalaryAmount ?? 0).roundTo(2)))元"))
                self.selectdata.append(("未付工资：","\((self.entity?.Result?.NonPaySalaryAmount ?? 0).roundTo(2))元"))
                if !(self.entity?.Result?.AdvaceSalaryAmount == nil||self.entity?.Result?.AdvaceSalaryAmount == 0){
                    self.selectdata.append(("垫付工资","\((self.entity?.Result?.AdvaceSalaryAmount ?? 0).roundTo(2))元"))
                    self.selectdata.append(("已付工资：","垫付工资("+"\((self.entity?.Result?.AdvaceSalaryAmount ?? 0).roundTo(2))元)"+"\((self.entity?.Result?.PayedSalaryAmount ?? 0).roundTo(2))元"))
                }else{
                    self.selectdata.append(("已付工资：","\((self.entity?.Result?.PayedSalaryAmount ?? 0).roundTo(2))元"))
                }
            }else if (self.entity?.Result?.IsSignSalary)! && !(self.entity?.Result?.IsFlat)!{
                if !(self.entity?.Result?.AdvaceSalaryAmount == nil||self.entity?.Result?.AdvaceSalaryAmount == 0){
                    self.selectdata.append(("垫付工资","\((self.entity?.Result?.AdvaceSalaryAmount ?? 0).roundTo(2))元"))
                    self.selectdata.append(("已付工资：","垫付工资("+"\((self.entity?.Result?.AdvaceSalaryAmount ?? 0).roundTo(2))元)"+"\((self.entity?.Result?.PayedSalaryAmount ?? 0).roundTo(2))元"))
                }else{
                    self.selectdata.append(("已付工资：","\((self.entity?.Result?.PayedSalaryAmount ?? 0).roundTo(2))元"))
                }
                self.selectdata.append(("未付工资：","\((self.entity?.Result?.NonPaySalaryAmount ?? 0).roundTo(2))元"))
            }else if !(self.entity?.Result?.IsSignSalary)!{
                if !(self.entity?.Result?.AdvaceSalaryAmount == nil||self.entity?.Result?.AdvaceSalaryAmount == 0){
                    self.selectdata.append(("垫付工资","\((self.entity?.Result?.AdvaceSalaryAmount ?? 0).roundTo(2))元"))
                    self.selectdata.append(("已付工资：","垫付工资("+"\((self.entity?.Result?.AdvaceSalaryAmount ?? 0).roundTo(2))元)"+"\((self.entity?.Result?.PayedSalaryAmount ?? 0).roundTo(2))元"))
                }else{
                    self.selectdata.append(("已付工资：","\((self.entity?.Result?.PayedSalaryAmount ?? 0).roundTo(2))元"))
                }
            }
            
            
            self.selectdata.append(("","余额明细"))
            print("count--->\(self.selectdata.count)")
            self.totaltableHeight.constant = CGFloat(self.selectdata.count) * self.rowSelectHeight
            self.totaltableview.layoutIfNeeded()
            
            self.selectvariable.onNext(self.selectdata)
            
            self.getTotalList()
        }) { (error) in
            switch error{
            case .DATAERROR:
                self.addTotalEmpty("数据异常")
                break;
            case .DATAFAIL:
                break;
            case .HTTPERROR:
                self.addTotalEmpty("网络异常")
                break;
            case .StateFail(let obj):
                guard let data = obj as? [String:Any] else{
                    self.addTotalEmpty("数据异常")
                    return
                }
                self.addTotalEmpty("\(data["Msg"] as? String ?? "")")
                break
            }
        }
    }
    
    
    func getTotalList(){
        var params:[String:Any] = ["pageIndex":"\(self.page)","pageSize":"\(PageSize)","constructionProjectID":ProjectId as! String]
        
        MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .GZTotalList, params: &params, type: GZTotalList.self, success: { (bean,_) in
            let b = bean as! GZTotalList
            if self.page == 1{
                self.data.removeAll()
                if !(!((self.entity?.Result?.IsSignSalary)!) && !((self.entity?.Result?.IsFlat)!)){
                    if (self.entity?.Result?.NonBalanceSalaryAmount ?? 0) != 0{
                        let v = GZTotalItem(LastUpdateTime: "", SalaryMonths: "待结算", SalaryState: "", PayAmount: (self.entity?.Result?.NonBalanceSalaryAmount ?? 0), DeductionCount: 0)
                        self.data.append(v)
                    }
                }
                
                
                if b.Result?.SalaryList?.count == nil || (b.Result?.SalaryList?.count)! == 0{
                    self.addEmptyView("暂无数据")
                }else if (b.Result?.SalaryList?.count ?? 0) < PageSize{
                    //SVProgressHUD.showInfo(withStatus: "暂无更多数据")
                    //self.tableNormalFoot?.stateLabel.isHighlighted = false
                }
                self.tableview.mj_header.endRefreshing()
                self.tableview.mj_footer.endRefreshing()
                
            }else{
                if (b.Result?.SalaryList?.count ?? 0) < PageSize{
                    //SVProgressHUD.showInfo(withStatus: "暂无更多数据")
                    self.tableNormalFoot?.stateLabel.isHighlighted = false
                    self.tableview.mj_footer.endRefreshingWithNoMoreData()
                }else{
                    self.tableview.mj_footer.endRefreshing()
                }
                
                
            }
            
            self.data.append(contentsOf: (b.Result?.SalaryList)!)
            self.datavariable.onNext(self.data)
        }) { (error) in
            switch error{
            case .DATAERROR:
                break;
            case .DATAFAIL:
                break;
            case .HTTPERROR:
                self.addEmptyView("网络异常")
                break;
            case .StateFail(let obj):
                guard let data = obj as? [String:Any] else{
                    self.addEmptyView("网络异常")
                    return
                }
                self.addEmptyView(data["Msg"] as? String ?? "")
                break
            }
               
            
        }
    }
    
    
        func addEmptyView(_ titleStr:String){
            guard let view = emptyview else {
                self.emptyview = EmptyView(frame: CGRect.zero, _title: titleStr, _top: Float(SCREEN_HEIGHT/5))
                self.view.addSubview(self.emptyview!)
                self.emptyview!.snp.updateConstraints({ (maker) in
                    maker.top.equalTo(self.selectline.snp.bottom)
                    maker.left.equalTo(self.view.snp.left)
                    maker.right.equalTo(self.view.snp.right)
                    maker.bottom.equalTo(self.view.snp.bottom)
                })
                return
            }
        }
    func addTotalEmpty(_ titleStr:String){
        guard let view = emptyview else {
            self.emptyview = EmptyView(frame: CGRect.zero, _title: titleStr, _top: Float(SCREEN_HEIGHT/5))
            self.view.addSubview(self.emptyview!)
            self.emptyview!.snp.updateConstraints({ (maker) in
                maker.top.equalTo(self.view.snp.top)
                maker.left.equalTo(self.view.snp.left)
                maker.right.equalTo(self.view.snp.right)
                maker.bottom.equalTo(self.view.snp.bottom)
            })
            return
        }
        
    }
    
    
    
    func removeEmpty(){
        guard let view = emptyview else {
            return;
        }
        self.emptyview?.removeFromSuperview()
        self.emptyview = nil
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
